package com.flowable.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.flowable.project.mapper.FlowableAliyunInfoBindMapper;
import com.flowable.project.mapper.FlowableDingdingInfoBindMapper;
import com.flowable.project.model.FlowableAliyunInfoBind;
import com.flowable.project.model.FlowableDingDingInfoBind;
import com.flowable.project.model.request.InfoBind;
import com.flowable.project.service.InfoBindService;
import org.flowable.engine.RuntimeService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class InfoBindServiceImpl implements InfoBindService {
    @Autowired
    private FlowableAliyunInfoBindMapper flowableAliyunInfoBindMapper;

    @Autowired
    private FlowableDingdingInfoBindMapper flowableDingdingInfoBindMapper;

    @Autowired
    private RuntimeService runtimeService;

    @Override
    public void saveInfo(InfoBind infoBind) {
        FlowableAliyunInfoBind flowableAliyunInfoBind = new FlowableAliyunInfoBind();
        FlowableDingDingInfoBind flowableDingDingInfoBind = new FlowableDingDingInfoBind();
        flowableAliyunInfoBind.setExecutionId(infoBind.getExecutionId());
        flowableDingDingInfoBind.setExecutionId(infoBind.getExecutionId());
        List<String> topics = infoBind.getTopics();
        for (String topic:topics){
            flowableAliyunInfoBind.setAliyunTopic(topic);
            flowableAliyunInfoBindMapper.insert(flowableAliyunInfoBind);
        }
        List<String> dingdingProcessId = infoBind.getDingdingProcessId();
        for (String processid:dingdingProcessId){
            flowableDingDingInfoBind.setDingdingProcessId(processid);
            flowableDingdingInfoBindMapper.insert(flowableDingDingInfoBind);
        }
    }

    @Override
    public void sendMessageByTopic(String topic, Map<String,Object> data) {
        FlowableAliyunInfoBind flowableAliyunInfoBind = flowableAliyunInfoBindMapper.selectOne(new QueryWrapper<FlowableAliyunInfoBind>().eq("aliyun_topic", topic));
        runtimeService.messageEventReceived(topic,flowableAliyunInfoBind.getExecutionId(),data);
    }

    @Override
    public void sendMessageByProcessId(String processId,Map<String,Object> data) {
        FlowableDingDingInfoBind flowableDingDingInfoBind = flowableDingdingInfoBindMapper.selectOne(new QueryWrapper<FlowableDingDingInfoBind>().eq("dingding_process_id", processId));
        runtimeService.messageEventReceived(processId,flowableDingDingInfoBind.getExecutionId(),data);
    }
}
